package com.qf.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.qf.entity.HouseType;
import com.qf.mapper.HouseTypeMapper;
import com.qf.service.HouseTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.SimpleFormatter;

@Service
public class HouseTypeServiceImpl implements HouseTypeService {
    @Autowired
    private HouseTypeMapper mapper;

    @Override
    public List<Tree<String>> getHouseType() {
        // 查询全部房屋分类
        List<HouseType> houseTypes = mapper.selectAll();

        // 配置树节点
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 设置深度限制为3级
        treeNodeConfig.setDeep(3);

        // 创建时间格式化器
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 构建树形结构
        List<Tree<String>> trees = TreeUtil.build(houseTypes, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId().toString());
                    tree.setParentId(treeNode.getParentId().toString());
                    tree.setName(treeNode.getName());

                    // 添加额外属性
                    tree.putExtra("level", treeNode.getLevel());
                    tree.putExtra("displayOrder", treeNode.getDisplayOrder());
                    tree.putExtra("createTime", format.format(treeNode.getCreateTime()));
                    tree.putExtra("roomPrice", treeNode.getRoomPrice());
                    tree.putExtra("description", treeNode.getDescription());
                    tree.putExtra("landlordName", treeNode.getLandlordName());
                    tree.putExtra("remainingRooms", treeNode.getRemainingRooms());
                    tree.putExtra("phone",treeNode.getPhone() );
                    tree.putExtra("reservedField2", treeNode.getReservedField2());
                });
        return trees;
    }

    @Override
    public boolean deleteHouseType(Integer id) {
        return mapper.deleteHouseType(id);
    }

    @Override
    public boolean addHouseType(HouseType houseType) {
        //计算level，先查找他的父节点level字段，再加1
       Integer parentId =  houseType.getParentId();
        HouseType parent = mapper.selectParentById(parentId);
        if(parent!= null){
            houseType.setLevel(parent.getLevel() + 1);
        }else{
            houseType.setLevel(1);
        }

        return mapper.addHouseType(houseType);
    }

    @Override
    public boolean updateHouseType(HouseType houseType) {
        return mapper.updateHouseType(houseType);
    }


}
